<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="巡检单号" prop="recordCode">
        <el-input
          v-model="queryParams.recordCode"
          placeholder="请输入巡检单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="巡检状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择巡检状态" clearable size="small">
          <el-option label="待巡检" value="0" />
          <el-option label="巡检中" value="1" />
          <el-option label="已完成" value="2" />
          <el-option label="已取消" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="巡检日期">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="recordList"
    >
      <el-table-column label="巡检单号" align="center" prop="recordCode" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" :show-overflow-tooltip="true" />
      <el-table-column label="巡检开始时间" align="center" prop="startTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="巡检人员" align="center" prop="inspectorName" />
      <el-table-column label="巡检状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '0'" type="warning">待巡检</el-tag>
          <el-tag v-if="scope.row.status === '1'" type="primary">巡检中</el-tag>
          <el-tag v-if="scope.row.status === '2'" type="success">已完成</el-tag>
          <el-tag v-if="scope.row.status === '3'" type="info">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleExecute(scope.row)"
            v-hasPermi="['sb:inspection-record:edit']"
            v-if="scope.row.status === '0' || scope.row.status === '1'"
          >执行巡检</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listInspectionRecord, getInspectionRecord, updateInspectionRecord, startInspection } from "@/api/sb/inspectionRecord";
import request from '@/utils/request';

export default {
  name: "InspectionRecord",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡检记录表格数据
      recordList: [],
      // 日期范围
      dateRange: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recordCode: null,
        equipmentName: null,
        status: null,
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // 检查是否需要刷新数据
    if (this.$route.query.refresh) {
      console.log("检测到刷新参数，重新加载数据");
      this.getList();
    }
  },
  watch: {
    // 监听路由变化，当从其他页面返回时刷新数据
    '$route'(to, from) {
      if (to.query.refresh) {
        console.log("路由变化，检测到刷新参数");
        this.$nextTick(() => {
          this.getList();
        });
      }
    }
  },
  methods: {
    /** 查询巡检记录列表 */
    getList() {
      this.loading = true;
      listInspectionRecord(this.queryParams).then(response => {
        this.recordList = response.rows;
        
        // 计算每条记录的预计结束时间（基于巡检计划的设置）
        this.recordList.forEach(record => {
          // 如果有开始时间但没有预计结束时间，则尝试计算
          if (record.startTime && !record.expectedEndTime && record.planId) {
            // 根据计划类型和开始时间估算结束时间
            // 默认设置为开始时间后2小时
            const startTime = new Date(record.startTime);
            const expectedEndTime = new Date(startTime);
            expectedEndTime.setHours(expectedEndTime.getHours() + 2);
            record.expectedEndTime = expectedEndTime;
          }
        });
        
        this.total = parseInt(response.total) || 0;
        this.loading = false;
      }).catch(error => {
        console.error("获取巡检记录列表失败", error);
        this.recordList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 执行巡检按钮操作 */
    handleExecute(row) {
      if (row.status === '0') {
        // 待巡检状态，先调用开始巡检接口
        this.$modal.confirm('确认开始执行巡检？').then(() => {
          this.$modal.loading("正在开始巡检...");
          
          // 调用后端接口开始执行巡检
          const recordId = row.recordId;
          return startInspection(recordId);
        }).then(response => {
          this.$modal.closeLoading();
          if (response.code === 200) {
            this.$message.success("开始执行巡检");
            // 添加refresh参数，返回时自动刷新
            this.$router.push({ 
              path: '/sb/Inspection-list/execute/' + row.recordId,
              query: { fromList: true }
            });
          } else {
            this.$modal.msgError(response.msg || "操作失败");
          }
        }).catch(() => {
          this.$modal.closeLoading();
        });
      } else {
        // 如果是巡检中状态，直接跳转到执行页面
        this.$router.push({ 
          path: '/sb/Inspection-list/execute/' + row.recordId,
          query: { fromList: true }
        });
      }
    },
    
    /** 详情按钮操作 */
    handleDetail(row) {
      this.$router.push({ 
        path: '/sb/Inspection-list/detail/' + row.recordId,
        query: { fromList: true }
      });
    }
  }
};
</script> 

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style> 